package org.zjvis.datascience.service;

import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zjvis.datascience.common.constant.Constant;
import org.zjvis.datascience.common.enums.PythonDateTypeFormatEnum;
import org.zjvis.datascience.service.dataprovider.GPDataProvider;

import javax.servlet.ServletContext;

/**
 * @description Date 日期 Service
 * @date 2021-10-18
 */
@Service
public class DateService {

    @Autowired
    private ServletContext servletContext;

    @Autowired
    private GPDataProvider gpDataProvider;

    public boolean checkStdDate(String table, String col){
        String dataSourceKey = (String) servletContext.getAttribute(Constant.DEFAULT_DATA_SOURCE_KEY);

        String sql = String.format("select distinct(\"%s\"::varchar ~ '^\\d{4}.\\d{2}.\\d{2}|^\\d{2}:\\d{2}:\\d{2}') as check from %s limit 5000", col, table);
        JSONArray ret = gpDataProvider.executeQuerySQL(dataSourceKey,sql,JSONArray.class);
        if (ret.size() == 1 && ret.getJSONObject(0).getBoolean("check")){
            return true;
        } else {
            return false;
        }
    }

    public String formatTime(String table, String col){
        if (checkStdDate(table, col)){
            return col;
        } else {
            return String
                .format("pipeline.sys_func_format_time(\"%s\"::varchar, '%s')", col,
                    PythonDateTypeFormatEnum.FORMAT_0.getVal());
        }
    }
}
